package
{
	import dev.touchswipe.shared.Animation.Animation;
	import dev.touchswipe.shared.Fonts;
	import dev.touchswipe.shared.components.Checkbox;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageDisplayState;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.FullScreenEvent;
	import flash.events.MouseEvent;
	import flash.events.TouchEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Matrix;
	import flash.geom.PerspectiveProjection;
	import flash.geom.Point;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.ui.Multitouch;
	import flash.ui.MultitouchInputMode;
	import flash.utils.ByteArray;
	
	import ui.Tile;
	import ui.TileContainer;
	import ui.icons.TileIcons;
	import ui.icons.fileIcon;
	import ui.icons.folderIcon;
	
	import utils.DirectoryBrowser;
	import utils.DirectoryBrowserEvent;
	
	[SWF(backgroundColor="#000000")]
	
	public class FileBrowser extends Sprite
	{
		private var tileContainer:TileContainer;
		private var _mask:Shape;
		private var currentPath:TextField;
		private var dir:DirectoryBrowser
		private var showIcons:Checkbox;
		public function FileBrowser()
		{
			super();
			stage.scaleMode=StageScaleMode.NO_SCALE;
			stage.align=StageAlign.TOP_LEFT;
			Multitouch.inputMode=MultitouchInputMode.TOUCH_POINT;
			
			showIcons=new Checkbox();
			showIcons.addEventListener(Event.SELECT,function(event:Event):void{
				updateTiles(tileContainer,dir);
			});
			showIcons.checked=false;
			showIcons.x=10;
			showIcons.y=13;
			
			dir=new DirectoryBrowser(File.documentsDirectory);
			dir.addEventListener(DirectoryBrowserEvent.DIRECTORY_CHANGED,onDirectoryChanged);
			dir.addEventListener(DirectoryBrowserEvent.DIRECTORY_UP,onDirectoryChanged);
			
			tileContainer=new TileContainer(stage.stageWidth,stage.stageHeight-40);
			tileContainer.y=40;
			addChild(tileContainer);
			updateTiles(tileContainer,dir);
			
			_mask=new Shape();
			_mask.graphics.beginFill(0);
			_mask.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight-40);
			_mask.y=40;
			addChild(_mask);
			tileContainer.mask=_mask;
			
			currentPath=new TextField();
			currentPath.defaultTextFormat=new TextFormat(Fonts.SegoeUIL,30,0xFFFFFF);
			currentPath.embedFonts=true;
			currentPath.text=dir.currentDir.nativePath;
			currentPath.selectable=false;
			currentPath.width=stage.stageWidth-300;
			currentPath.x=300;
			currentPath.height=40;
			addChild(currentPath);
			
			var showIconsLabel:TextField=new TextField();
			showIconsLabel.defaultTextFormat=new TextFormat(Fonts.SegoeUIL,16,0xFFFFFF);
			showIconsLabel.embedFonts=true;
			showIconsLabel.text="Use System Icons (Slower)";
			showIconsLabel.x=25;
			showIconsLabel.y=5;
			showIconsLabel.width=250;
			showIconsLabel.height=30;
			addChild(showIcons);
			addChild(showIconsLabel);
			
			stage.addEventListener(Event.RESIZE,onStageResize);
			stage.addEventListener(TouchEvent.TOUCH_BEGIN,onTouchBegin);
			stage.addEventListener(TouchEvent.TOUCH_END,onTouchEnd);
			addEventListener(Event.ENTER_FRAME,onEnterFrame);
		}
		
		public function updateTiles(container:TileContainer,directory:DirectoryBrowser):void{
			container.clear();
			var i:int=0;
			var j:int=0;
			var k:int=0;
			var ico:DisplayObject;
			var n:int=0;
			for each(var f:File in directory.getListing()){
				n++;
				if(!f.isHidden){
					if(showIcons.checked){
						var bmpData:BitmapData=new BitmapData(1,1);
						for (var b:int = 0; b < f.icon.bitmaps.length; b++)
							if (f.icon.bitmaps[b].height > bmpData.height)
								bmpData = f.icon.bitmaps[b];
						ico=new Bitmap(bmpData);
					}
					else{
						if(f.isDirectory)
							ico=new folderIcon();
						else
							ico=new fileIcon();
					}
					var tile:Tile=new Tile(i,j,k,f.name,ico);
					tile.addEventListener(MouseEvent.CLICK,function(event:MouseEvent):void{
						directory.select(event.currentTarget.value);
					});
					container.addTile(tile);
					i++;
					if(i==6){
						j++;
						i=0;
					}
					if(j==3){
						k++;
						j=0;
					}
				}
			}
			container.updateZoom(0);
		}
		
		public function onDirectoryChanged(event:DirectoryBrowserEvent):void{
			currentPath.text=dir.currentDir.nativePath;
			if(event.type==DirectoryBrowserEvent.DIRECTORY_UP)
				tileContainer.x=-stage.stageWidth/3;
			else 
				tileContainer.x=stage.stageWidth/3;
			updateTiles(tileContainer,dir);
		}
		
		public function onStageResize(event:Event):void{
			_mask.graphics.beginFill(0);
			_mask.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight-40);
			
			currentPath.width=stage.stageWidth-300;
			
			tileContainer.displayWidth=stage.stageWidth;
			tileContainer.displayHeight=stage.stageHeight-40;
			
			var projection:PerspectiveProjection=new PerspectiveProjection();
			projection.projectionCenter=new Point(stage.stageWidth/2,stage.stageHeight/2);
			transform.perspectiveProjection=projection;
			
			drawBackground();
		}
		
		private function drawBackground():void{
			/*/
			var fs:FileStream=new FileStream();
			var file:File=File.applicationDirectory;
			file=file.resolvePath("background.png");
			fs.open(file,FileMode.READ);
			var loader:Loader=new Loader();
			var data:ByteArray=new ByteArray();
			fs.readBytes(data);
			loader.loadBytes(data);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,function(event:Event):void{
				var bmpData:BitmapData=Bitmap(loader.content).bitmapData;
				var transform:Matrix=new Matrix();
				transform.createBox(stage.stageWidth/bmpData.width,stage.stageHeight/bmpData.height);
				graphics.beginBitmapFill(bmpData,transform,false,true);
				graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight);
				graphics.endFill();
				fs.close();
			});
			//*/
		}
		
		private var _offsetY:Number=0;
		private var _offsetX:Number=0;
		private var _isDragging:Boolean=false;
		private var _startTime:Date;
		private var _touchId:Object=null;
		
		public function onTouchBegin(event:TouchEvent):void{
			if(_touchId==null){
				_touchId=event.touchPointID;
				_startTime=new Date();
				_isDragging=true;
				_offsetY=event.stageY;
				_offsetX=event.stageX-tileContainer.x;
				stage.addEventListener(TouchEvent.TOUCH_MOVE,onTouchMove);
			}
		}
		
		public function onTouchMove(event:TouchEvent):void{
			if(event.touchPointID==_touchId){
				var zoom:Number=(event.stageY-_offsetY)/2;
				if(tileContainer.zoom>0&&event.stageY-_offsetY>0)
					zoom*=(100-tileContainer.zoom)/100;
				else if(tileContainer.zoom<(-100*(tileContainer.layers-0.6))&&event.stageY-_offsetY<0)
					zoom*=(tileContainer.zoom+100*(tileContainer.layers+0.4))/100;
				tileContainer.zoom+=zoom;
				var x:Number=(event.stageX-_offsetX)/800;
				tileContainer.x=0.3*stage.stageWidth*(2/(1+Math.exp(-x))-1);
				_offsetY=event.stageY;
				event.updateAfterEvent();
			}
		}
		
		public function onTouchEnd(event:TouchEvent):void{
			if(event.touchPointID==_touchId){
				if(new Date().getTime()-_startTime.getTime()<250&&Math.abs(event.stageX-_offsetX)>150)
					dir.up();
				_touchId=null;
				_isDragging=false;
				stage.removeEventListener(TouchEvent.TOUCH_MOVE,onTouchMove);
			}
		}
		
		public function onEnterFrame(event:Event):void{
			if(!_isDragging){
				var target:Number=Math.floor(tileContainer.zoom/100+0.3)*100;
				if(target>0)
					target=0;
				if(target<-(tileContainer.layers)*100){
					target=-(tileContainer.layers)*100;
				}
				if(Math.abs(target-tileContainer.zoom)>1)
					tileContainer.zoom+=(target-tileContainer.zoom)/5;
				else if(tileContainer.zoom!=target)
					tileContainer.zoom=target;
				if(Math.abs(tileContainer.x)>5)
					tileContainer.x*=0.5;
				else tileContainer.x=0;
				
			}
			
		}
	}
}